package org.wdcode.web.socket.client;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

import org.wdcode.common.exception.CustomRuntimeException;

/**
 * UDP Socket客户端实现
 * @author WD
 * @since JDK6
 * @version 1.0 2010-01-29
 */
final class SocketClientUDPImpl implements SocketClientUDP {
	// JDK UDP Socket
	private DatagramSocket	socket;

	/**
	 * 构造方法
	 */
	public SocketClientUDPImpl() {
		try {
			socket = new DatagramSocket();
		} catch (SocketException e) {
			throw new CustomRuntimeException(e);
		}
	}

	/**
	 * 构造方法
	 * @param host 主机
	 * @param port 端口
	 */
	public SocketClientUDPImpl(String host, int port) {
		try {
			socket = new DatagramSocket(new InetSocketAddress(host, port));
		} catch (SocketException e) {
			throw new CustomRuntimeException(e);
		}
	}

	/**
	 * 断开连接
	 */
	public void disconnect() {
		socket.disconnect();
	}

	/**
	 * 接收数据
	 * @param b 字节数组
	 */
	public byte[] receive(byte[] b) {
		try {
			// 声明UDP数据包
			DatagramPacket p = new DatagramPacket(b, b.length);
			// 接收数据
			socket.receive(p);
			// 返回数据
			return p.getData();
		} catch (IOException e) {
			throw new CustomRuntimeException(e);
		}
	}

	/**
	 * 发送数组
	 * @param b 字节数组
	 */
	public void send(byte[] b) {
		try {
			// 声明UDP数据包
			DatagramPacket p = new DatagramPacket(b, b.length);
			// 发送数据
			socket.send(p);
		} catch (IOException e) {
			throw new CustomRuntimeException(e);
		}
	}

	/**
	 * 绑定到一台服务器上
	 * @param host 服务器地址
	 * @param port 服务器端口
	 */
	public void bind(String host, int port) {
		try {
			socket.bind(new InetSocketAddress(host, port));
		} catch (SocketException e) {
			throw new CustomRuntimeException(e);
		}
	}

	/**
	 * 连接到服务器
	 * @param host 服务器地址
	 * @param port 服务器端口
	 */
	public void connect(String host, int port) {
		try {
			socket.connect(new InetSocketAddress(host, port));
		} catch (SocketException e) {
			throw new CustomRuntimeException(e);
		}
	}

	/**
	 * 连接到服务器
	 * @param host 服务器地址
	 * @param port 服务器端口
	 * @param timeout 超时时间
	 */
	public void connect(String host, int port, int timeout) {
		try {
			socket.connect(new InetSocketAddress(host, port));
		} catch (SocketException e) {
			throw new CustomRuntimeException(e);
		}
	}

	/**
	 * 返回连接服务器的地址
	 * @return 服务器地址
	 */
	public String getInetAddress() {
		return socket.getInetAddress().toString();
	}

	/**
	 * 返回本机端口
	 * @return 本机端口
	 */
	public int getLocalPort() {
		return socket.getLocalPort();
	}

	/**
	 * 返回本机地址
	 * @return 本机地址
	 */
	public String getLocalSocketAddress() {
		return socket.getLocalSocketAddress().toString();
	}

	/**
	 * 返回连接服务器的端口
	 * @return 服务器端口
	 */
	public int getPort() {
		return socket.getPort();
	}

	/**
	 * 关闭资源
	 */
	public void close() {
		socket.close();
	}
}
